package cn.kgc.javaweb.servlet;

import cn.hutool.json.JSONUtil;
import cn.kgc.javaweb.dto.UserPageDTO;
import cn.kgc.javaweb.entity.Unit;
import cn.kgc.javaweb.service.UnitService;
import cn.kgc.javaweb.service.impl.UnitServiceImpl;
import cn.kgc.javaweb.util.JsonResultWriter;
import cn.kgc.javaweb.util.ResponseResult;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/unit")
public class UnitServlet extends BaseServlet {

    private UnitService unitService = new UnitServiceImpl();

    // 用户信息分页查询  查询所有用户信息分页    搜索用户信息分页//
    protected void selectPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer page = Integer.valueOf(req.getParameter("page"));
        Integer limit = Integer.valueOf(req.getParameter("limit"));
        String searchParams = req.getParameter("searchParams");


        UserPageDTO userPageDTO = UserPageDTO.builder().limit(limit).page(page).searchParams(searchParams).build();
        ResponseResult responseResult = unitService.selectPage(userPageDTO);
        JsonResultWriter.writerJson(resp, responseResult);

    }


    // 根据id 查询用户信息//
    protected void selectById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.valueOf(req.getParameter("id"));
        ResponseResult responseResult = unitService.selectById(id);
        JsonResultWriter.writerJson(resp, responseResult);

    }


    // 修改用户信息//
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // json 字符串
        String unit = req.getParameter("unit");
        Integer id = Integer.valueOf(req.getParameter("id"));

        Unit uni = JSONUtil.toBean(unit, Unit.class);
        System.out.println("usr = " + uni);

        ResponseResult responseResult = unitService.update(uni,id);
        JsonResultWriter.writerJson(resp, responseResult);

    }

    // 添加用户信息//
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String unit = req.getParameter("unit");
        Unit uni = JSONUtil.toBean(unit, Unit.class);
        System.out.println("uni = " + uni);
        ResponseResult responseResult = unitService.add(uni);
        JsonResultWriter.writerJson(resp, responseResult);
    }

    // 删除用户信息//
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String ids = req.getParameter("ids");

        ResponseResult responseResult =  unitService.delete(ids);
        JsonResultWriter.writerJson(resp, responseResult);


    }


}
